/**
 * 认证API接口
 */
import axios from 'axios'

// 使用相对路径，通过Vite代理访问后端，避免CORS问题
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api/v1'

const authApi = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // 支持跨域携带cookie
})

// 响应拦截器
authApi.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    return Promise.reject(error)
  }
)

export interface LoginRequest {
  username: string
  password: string
}

export interface LoginResponse {
  success: boolean
  access_token: string
  token_type: string
  user: {
    id: number
    username: string
    email?: string
    role: string
  }
}

export interface RegisterRequest {
  username: string
  password: string
  email?: string
  phone?: string
}

export interface RegisterResponse {
  success: boolean
  message: string
  user: {
    id: number
    username: string
    email?: string
  }
}

/**
 * 用户登录
 */
export const login = (data: LoginRequest): Promise<LoginResponse> => {
  return authApi.post('/auth/login', data)
}

/**
 * 用户注册
 */
export const register = (data: RegisterRequest): Promise<RegisterResponse> => {
  return authApi.post('/auth/register', data)
}

/**
 * 获取当前用户信息（验证token）
 */
export const getCurrentUser = (token: string): Promise<any> => {
  return authApi.get('/auth/verify', {
    headers: {
      Authorization: `Bearer ${token}`
    }
  })
}

/**
 * 退出登录
 */
export const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
}

export default authApi

